package com.qf.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.qf.config.AlipayConfig;
import com.qf.pojo.*;
import com.qf.service.OrderService;
import com.qf.service.impl.OrderServiceImpl;
import com.qf.utils.UUIDUtils;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * 订单的后端访问地址
 */
@SuppressWarnings("all")
@WebServlet("/order")
public class OrderServlet extends BaseServlet {

    /**
     *生成订单信息和订单项信息
     * @param request 请求对象
     * @param response 响应对象
     */
    public void generateOrder(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
        //封装订单数据之前,从request域中获取HttpSession,是否有用户信息;如果没有,继续登录
       User user = (User) request.getSession().getAttribute("user");
       if(user==null){
           //重定向登录页面中
           response.sendRedirect(request.getContextPath()+"/jsp/login.jsp");
           return;
       }

        //封装订单
        Order order  = new Order() ;
        //订单编号
        order.setOid(UUIDUtils.getId()) ;
        //下订单时间
        order.setOrdertime(new Date()) ;

        //从HttpSession获取购物车
        Cart cart = (Cart) request.getSession().getAttribute("cart") ;
        //获取购物车中的总金额
        order.setTotal(cart.getTotalMoney()) ;
        //收货地址/电话/收货人
        //封装订单项----包含的商品/数量/小计--都来自于购物车CartItem
        OrderItem orderItem = null ;
        for(CartItem cartItem:cart.getCartItems()){
            //获取到每一个购物车项
            orderItem = new OrderItem() ;
            //订单项itemid
            orderItem.setItemid(UUIDUtils.getId()) ;
            orderItem.setCount(cartItem.getCount()) ;
            orderItem.setSubtotal(cartItem.getSubTotal()) ;
            orderItem.setProduct(cartItem.getProduct()) ;
            orderItem.setOrder(order) ; //属于哪个订单

            //订单里面添加多个订单项数据
            List<OrderItem> list = order.getList();
            list.add(orderItem) ;
        }
        //这个订单属于哪个用户的
        order.setUser(user) ;


        System.out.println(order) ;
        System.out.println(orderItem);

        //调用订单业务接口
        OrderService orderService = new OrderServiceImpl() ;
        orderService.addOrder(order) ;


        //将购物车里面的数据删除了
        request.getSession().removeAttribute("cart") ;
        //将Order实体存储在request域中
        request.setAttribute("order",order) ;
        //请求转发到/jsp/order_info.jsp
        request.getRequestDispatcher("/jsp/order_info.jsp").forward(request,response);

    }


    /**
     * 获取订单列表的功能
     * @param request 请求对象
     * @param response 响应对象
     */
    public void getOrderListByPage(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        //1)接收参数
        //${pageContext.request.contextPath}/order?methodName=getOrderListByPage&curPage=1&pSize=3
        String curPage = request.getParameter("curPage") ;
        String pSize = request.getParameter("pSize") ;

        //转换成int
        int currentPage = Integer.parseInt(curPage) ;
        int pageSize =  Integer.parseInt(pSize) ;

        //2)从request域中获取HttpSession,获取User信息
        User user = (User) request.getSession().getAttribute("user") ;
        if(user==null){
            request.getRequestDispatcher("/jsp/login.jsp").forward(request,response) ;
            return ;
        }

        //3)调用业务接口
        OrderService orderService = new OrderServiceImpl() ;
        PageBean<Order> pb = orderService.getOrderListByPage(currentPage, pageSize, user);

        //4)存储在request域中
        request.setAttribute("pb",pb);
        request.getRequestDispatcher("/jsp/order_list.jsp").forward(request,response);

    }

    /**
     * 订单支付的功能---调用支付宝接口
     * @param request  请求对象
     * @param response  响应对象
     */
    public void pay(HttpServletRequest request,HttpServletResponse response){
            //接收参数:隐藏域 订单编号
        String oid = request.getParameter("oid");
        //System.out.println(oid);
        //调用订单业务接口---通过订单编号获取订单实体
        OrderService orderService = new OrderServiceImpl() ;
        Order order = orderService.getOrderByOid(oid);


        try {

            //获得初始化的AlipayClient (创建支付宝客户端对象)
            AlipayClient alipayClient = new DefaultAlipayClient(
                    AlipayConfig.gatewayUrl,
                    AlipayConfig.app_id,
                    AlipayConfig.merchant_private_key,
                    "json",
                    AlipayConfig.charset,
                    AlipayConfig.alipay_public_key,
                    AlipayConfig.sign_type);

            //设置请求参数---设置支付宝回调的参数
            AlipayTradePagePayRequest alipayRequest =
                    new AlipayTradePagePayRequest();
            alipayRequest.setReturnUrl(AlipayConfig.return_url);
            alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

            //设置发送请求的时候,里面的具体的参数:
            //1)out_trade_no:订单编号
            //2)subject：主题信息
            //3)product_code:产品码名称,支付宝默认值:FAST_INSTANT_TRADE_PAY
            //4)total_amount:总金额
            alipayRequest.setBizContent("{\"out_trade_no\":\""+ order.getOid() +"\","
                    + "\"total_amount\":\""+ order.getTotal() +"\","
                    + "\"subject\":\""+ "数码产品" +"\","
                    + "\"body\":\""+ "手机和电脑相关"+"\","
                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

//			//商户订单号，商户网站订单系统中唯一订单号，必填
//			String out_trade_no = "asdfgre13243245335345";
//			//付款金额，必填
//			String total_amount = "1";
//			//订单名称，必填
//			String subject = "充值话费";
//			//商品描述，可空
//			String body = "话费充值1元";
//
//			alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
//					+ "\"total_amount\":\""+ total_amount +"\","
//					+ "\"subject\":\""+ subject +"\","
//					+ "\"body\":\""+ body +"\","
//					+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

            //若想给BizContent增加其他可选请求参数，以增加自定义超时时间参数timeout_express来举例说明
            //alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
            //		+ "\"total_amount\":\""+ total_amount +"\","
            //		+ "\"subject\":\""+ subject +"\","
            //		+ "\"body\":\""+ body +"\","
            //		+ "\"timeout_express\":\"10m\","
            //		+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
            //请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节

            //请求
            //将设置表单信息全部以form表单方式发送支付宝
            String result = alipayClient.pageExecute(alipayRequest).getBody();
            //输出
            System.out.println(result);
            //响应给浏览器---->用户看到支付宝的登录页面
            response.getWriter().write(result) ;
            response.getWriter().flush();
            response.getWriter().close();
        } catch (AlipayApiException | IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}
